﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Ext.Net;
using Sio.Mdm.Entities;
using Sio.Mdm.Client;
using Sio.Mdm.BF.Idm;
using Sio.Mdm.BF.Sifranti;
using Sio.Mdm.Types.Database;
using Sio.Mdm.Types;
using Sio.Mdm.BF.Ldap;
using System.Collections.Generic;

namespace Sio.Mdm.Web.Organizacija
{
    public partial class UceciSeznam : Controls.Page
    {
        #region Definitions
        public interface UceciRowEditData
        {
            int IdmStevilka { get; set; }
            int VlogaId { get; set; }
            string Ime { get; set; }
            string Priimek { get; set; }
            int Spol { get; set; }
            string Naslov { get; set; }
            int PostaId { get; set; }
            int ObcinaId { get; set; }
        }
        #endregion

        private enum ClientNotification
        {
            LdapSyncSuccess,
            LdapDeleteSuccess,
            LdapSyncError,
            LdapDeleteError
        }

        #region Methods

        #region Protected

        #region OnLoad
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!IsPostBack && !X.IsAjaxRequest)
            {
                //občine
                EntityCollection<Obcina> obcine = new EntityCollection<Obcina>(
                  new Filter<Obcina>().Where(o => o.ObcinaId != null).OrderBy(o => o.Naziv));
                this.StoreObcine.DataSource = obcine;
                this.StoreObcine.DataBind();

                //pošte
                //var slServicePoste = ServiceFactory.GetService<IPostneStevilkeService>();
                EntityCollection<PostnaStevilka> postneStevilke = new EntityCollection<PostnaStevilka>(
                                    new Filter<PostnaStevilka>().Where(p => p.PostaId != null).OrderBy(p => p.PostnaStevilka));
                this.StorePoste.DataSource = postneStevilke;
                this.StorePoste.DataBind();

                //spoli
                Dictionary<int, string> listSpoli = new Dictionary<int, string>();
                listSpoli.Add(0, "moški");
                listSpoli.Add(1, "ženski");
                var tmpArray = (from p in listSpoli select new Object[2] { p.Key, p.Value }).ToArray();

                this.StoreSpoli.DataSource = tmpArray;
                this.StoreSpoli.DataBind();

                NaloziSeznamUcecih();
            }
        }
        #endregion

        #region Editing
        protected void UrediPodatke(Object sender, DirectEventArgs e)
        {
            UceciRowEditData EditData = XML.Deserialize<UceciRowEditData>(e.ExtraParams["data"]);
            Ucec ucec = EntityFactory.LoadEntity<Ucec>(
                new Filter<Ucec>().Where(r => r.IdmStevilka == EditData.IdmStevilka)
            );

            if (ucec.EntityState == EntityState.Unchanged)
            {
                ucec.Ime = EditData.Ime;
                ucec.Priimek = EditData.Priimek;
                ucec.Naslov = EditData.Naslov;

                ucec.PostaId = EditData.PostaId;
                if (ucec.PostaId < 1)
                {
                    ucec.PostaId = null;
                }

                ucec.ObcinaId = EditData.ObcinaId;
                if (ucec.ObcinaId < 1)
                {
                    ucec.ObcinaId = null;
                }

                ucec.Spol = EditData.Spol;
                ucec.Update();
            }
        }
        protected void OdstraniUcece(object sender, DirectEventArgs e)
        {
            List<int> deletedItems = e.GetIdList<int>("selected", "IdmStevilka");
            EntityCollection<Ucec> col = new EntityCollection<Ucec>(
                new Filter<Ucec>().SelectByField(r => r.IdmStevilka, deletedItems.ToArray())
            );

            col.RemoveAll();
            col.Update();
        }
        #endregion

        #region SyncToLdap*
        protected void SyncToLdapEvent(object sender, DirectEventArgs e)
        {
            int razredId = Request.GetValue<int>("razredid");
            List<int> selected = GetSelectedList(e.ExtraParams["selected"]);

            var slServiceLdap = ServiceFactory.GetService<ILdapService>();
            Result result = slServiceLdap.UserRequestSync(razredId, selected, this.UserSession);

            if (result == null)
                ShowClientNotification(ClientNotification.LdapSyncSuccess, "");
            else
                ShowClientNotification(ClientNotification.LdapSyncError, result.Message);
        }
        #endregion

        #region DeleteFromLdap*
        protected void DeleteFromLdapEvent(object sender, DirectEventArgs e)
        {
            int razredId = Request.GetValue<int>("razredid");
            List<int> selected = GetSelectedList(e.ExtraParams["selected"]);

            var slServiceLdap = ServiceFactory.GetService<ILdapService>();
            Result result = slServiceLdap.UserRequestDelete(razredId, selected, this.UserSession);

            if (result == null)
                ShowClientNotification(ClientNotification.LdapDeleteSuccess, "");
            else
                ShowClientNotification(ClientNotification.LdapDeleteError, result.Message);
        }
        #endregion

        #endregion

        #region Private
        private void NaloziSeznamUcecih()
        {
            //učeči
            int letoId = Request.GetValue<int>("letoid");
            int razredId = Request.GetValue<int>("razredid");//razred+paralelka
            int razred = Request.GetValue<int>("razred");//samo razred

            if (razredId > 0)
            {
                GridUceciSeznam.LoadData<Ucec>(
                    from r in new Filter<Ucec>()
                    join s in new Filter<UcecStatus>() on r.VlogaId equals s.VlogaId
                    join p in new Filter<RazredSkupina>() on s.RazredId equals p.RazredId
                    where
                        s.LetoId == letoId &&
                        p.LetoId == s.LetoId &&
                        s.RazredId == razredId &&
                        r.OrganizacijaId == this.UserSession.Organizacija
                    select r
                );
                //GridUceciSeznam.LoadData<Ucec, UcecStatus, RazredSkupina>(
                //    (r, s, p) => (r.VlogaId == s.VlogaId)
                //        && (s.LetoId == letoId) && (s.RazredId == razredId)
                //        && (p.RazredId == s.RazredId) && (p.LetoId == s.LetoId)
                //);
            }
            else if (razred > 0)
            {
                GridUceciSeznam.LoadData<Ucec>(
                    from r in new Filter<Ucec>()
                    join s in new Filter<UcecStatus>() on r.VlogaId equals s.VlogaId
                    join p in new Filter<RazredSkupina>() on s.RazredId equals p.RazredId
                    where
                       s.LetoId == letoId &&
                       p.Razred == razred &&
                       p.LetoId == s.LetoId &&
                       r.OrganizacijaId == this.UserSession.Organizacija
                    select r
                );
            }
            else
            {
                GridUceciSeznam.LoadData<Ucec>(
                    from r in new Filter<Ucec>()
                    join s in new Filter<UcecStatus>() on r.VlogaId equals s.VlogaId
                    join p in new Filter<RazredSkupina>() on s.RazredId equals p.RazredId
                    where
                       s.LetoId == letoId &&
                       p.LetoId == s.LetoId &&
                       r.OrganizacijaId == this.UserSession.Organizacija
                    select r
                );

                //        (r, s, p) => (r.VlogaId == s.VlogaId) && (s.LetoId == letoId)
                //        && (p.LetoId == s.LetoId) && (p.RazredId == s.RazredId) && (p.LetoId == s.LetoId)
                //);
            }
        }

        private List<int> GetSelectedList(string jsonString)
        {
            List<int> list = new List<int>();

            Dictionary<string, string>[] rows = JSON.Deserialize<Dictionary<string, string>[]>(jsonString);
            foreach (Dictionary<string, string> row in rows)
            {
                foreach (KeyValuePair<string, string> vals in row)
                {
                    if (vals.Key == "IdmStevilka")
                    {
                        list.Add(Int32.Parse(vals.Value));
                    }
                }
            }

            return list;
        }

        #region ShowClientNotification
        private void ShowClientNotification(ClientNotification clientNotification, string message)
        {
            string title = "";
            string html = "";
            Ext.Net.Icon icon = Icon.Information;

            switch (clientNotification)
            {
                case ClientNotification.LdapSyncSuccess:
                    title = "Ldap/AD Sinhronizacija";
                    html = "<b>Sinhronizacija je bila uspešna.</b> <br><br><i>Podatki so se uspešno sinhronizirali.</i>";
                    break;
                case ClientNotification.LdapDeleteSuccess:
                    title = "Ldap/AD Brisanje";
                    html = "<b>Brisanje je bilo uspešno.</b>";
                    break;
                case ClientNotification.LdapSyncError:
                    title = "Ldap/AD Sinhronizacija";
                    html = "<b>Napaka pri sinhronizaciji podatkov.</b>";
                    icon = Icon.Error;
                    break;
                case ClientNotification.LdapDeleteError:
                    title = "Ldap/AD Brisanje";
                    html = "<b>Napaka pri brisanju podatkov.</b>";
                    icon = Icon.Error;
                    break;
            }

            Notification.Show(new NotificationConfig
            {
                Title = title,
                Icon = icon,
                Html = html,
                HideDelay = 4000,
                Width = 200
            });
        }
        #endregion

        #endregion

        #endregion
    }
}
